package com.dx.financehy.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.DesensitizedUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Util {

    private static String[] NUMBERS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
    private static Random RANDOM = new Random();

    /**
     * 生成length位随机数值字符串
     *
     * @param length
     * @return
     */
    public static String randomCode(int length) {
        StringBuilder builder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            builder.append(NUMBERS[RANDOM.nextInt(NUMBERS.length)]);
        }

        return builder.toString();
    }

    public static String generatePassword(int length) {
        String result = getRandomPassword(length);
        if (BooleanUtil.toBoolean(PasswordValidation.checkPwd(result))) {
            return result;
        }
        return generatePassword(length);
    }

    public static String getRandomPassword(int length) {
        char charr[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~!@#$%^&*.?".toCharArray();
        StringBuilder sb = new StringBuilder();
        Random r = new Random();
        for (int x = 0; x < length; ++x) {
            sb.append(charr[r.nextInt(charr.length)]);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String s = generatePassword(8);
        String randomPassword = getRandomPassword(8);

        System.out.println(s);
        System.out.println(randomPassword);
    }

    //身份证、手机号脱敏
    public static Object FieldsDesensitized(Object object){
        Field[] declaredFields = object.getClass().getDeclaredFields();
        List<String> fieldNames = new ArrayList<String>() {{
            add("idNum");
            add("phone");
        }};
        Object obj = null;
        try {
            obj = BeanCopyUtil.copy(object, object.getClass());
            for(Field field : declaredFields){
                if (!fieldNames.contains(field.getName())) {
                    continue;
                }
                field.setAccessible(true);
                String str = (String) field.get(object);
                if("idNum".equals(field.getName())){
                    field.set(obj, DesensitizedUtil.idCardNum(str, 5, 2));
                }
                if("phone".equals(field.getName())){
                    field.set(obj,DesensitizedUtil.mobilePhone(str));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}
